import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const deleteEmptyDirArray = []
const deleteEmptyFileArray = []

async function deleteEmptyDirs(dir) {
  fs.readdirSync(dir).forEach((file) => {
    const filePath = path.join(dir, file)
    const stat = fs.statSync(filePath)
    const fileList = filePath.split('\\')

    if (stat.isDirectory()) {
      deleteEmptyDirs(filePath)
      if (fs.readdirSync(filePath).length === 0) {
        deleteEmptyDirArray.push(fileList[fileList.length - 1])

        fs.rmdirSync(filePath)
      }
    } else if (stat.isFile() && fs.statSync(filePath).size <= 1) {
      deleteEmptyFileArray.push(fileList[fileList.length - 1])

      fs.unlinkSync(filePath)
    }
  })
}

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const distDir = path.join(__dirname, '../dist')

// eslint-disable-next-line antfu/no-top-level-await
await deleteEmptyDirs(distDir)
console.log('删除dist中的空文件夹', deleteEmptyDirArray)
console.log('删除dist中的空文件', deleteEmptyFileArray)
